package com.qipay.api.wx.controller.v1;

import com.qipay.baas.model.Cp;
import com.qipay.baas.model.Order;
import com.qipay.cp.CpService;
import com.qipay.order.config.OrderStateEnum;
import com.qipay.order.service.OrderService;
import com.qipay.pay.WeiXinWapPayService;
import com.qipay.scalar.type.ApiStatusEnum;
import com.qipay.security.sign.service.SignService;
import com.qipay.sp.SpApiConfigService;
import com.qipay.sp.SpConfigService;
import com.qipay.utils.RequestUtils;
import com.qipay.utils.ResultUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/redirect/v1/wx")
public class WapPayRedirectController {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    CpService cpService;
    @Autowired
    SignService signService;

    @Autowired
    WeiXinWapPayService weiXinWapPayService;

    @Autowired
    OrderService orderService;

    @Autowired
    SpConfigService spConfigService;

    @Autowired
    SpApiConfigService spApiConfigService;

    @Value("${api.wx.wap.redirect.url}")
    String redirectUrl;

    @Value("${api.response.sign.name}")
    private String sigKey;


    @RequestMapping(value = "/wap", method = RequestMethod.GET, produces = {"application/xml;charset=UTF-8"})
    private ModelAndView wap(
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        Map<String,String> params = RequestUtils.getRequestParams(request);

        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        sb.deleteCharAt(sb.length()-1);
        String url = redirectUrl + "?" + sb.toString();
        response.sendRedirect(url);

        return null;
    }

    @RequestMapping(value = "/wap/pay", method = RequestMethod.GET, produces = {"application/xml;charset=UTF-8"})
    private ModelAndView pay(
            HttpServletRequest request,
            @RequestParam("mch_id") String mchId,
            @RequestParam("trade_no") String tradeNo,
            @RequestParam("nonce_str") String nonceStr,
            @RequestParam("sign") String sign,
            HttpServletResponse response
    ) throws Exception {
        Assert.notNull(mchId, "请输入商户ID");
        Assert.notNull(tradeNo, "请输入平台交易流水");
        Assert.notNull(nonceStr, "请输入随机字符串");
        Assert.notNull(sign, "请输入签名");

        Cp cp = cpService.getOneByAppId(mchId);
        Assert.notNull(cp,"错误的商户ID");

        Map<String, Object> params = new HashMap<>();
        params.put("mch_id",mchId);
        params.put("trade_no",tradeNo);
        params.put("nonce_str",nonceStr);
        params.put("sign",sign);
        String fromSig = params.get(sigKey).toString();
        String mySig = signService.getSign(params, cp.getSecretId(), sigKey);
        Assert.isTrue(StringUtils.equals(fromSig, mySig),"签名错误");

        Order order = orderService.getByTradeNo(tradeNo);
        Assert.notNull(order, "错误的订单信息");
        Assert.isTrue(mchId.equals(order.getCpId().toString()),"输入的商户号与订单信息不一致");
        Assert.isTrue(Objects.equals(order.getState(), OrderStateEnum.NOTPAY.getType()),
                ResultUtils.buildErrorMsg(ApiStatusEnum.ARGUMENT_ERR,"错误的订单信息"));

        Map<String, Object> payInfoMap =  weiXinWapPayService.wapPay(order.getId());

        Assert.notNull(payInfoMap,
                ResultUtils.buildErrorMsg(ApiStatusEnum.SERVICE_ERR,"请求sp的微信WAP支付失败"));
        Assert.isTrue(payInfoMap.containsKey("result_code"),
                ResultUtils.buildErrorMsg(ApiStatusEnum.SERVICE_ERR,"请求sp的微信WAP支付失败"));
        Assert.isTrue("0".equals(payInfoMap.get("result_code").toString()),
                ResultUtils.buildErrorMsg(ApiStatusEnum.SERVICE_ERR,"请求sp的微信WAP支付失败"));
        Assert.notNull(payInfoMap.get("pay_info"),
                ResultUtils.buildErrorMsg(ApiStatusEnum.SERVICE_ERR,"请求sp的微信WAP支付失败"));

        String payInfo = payInfoMap.get("pay_info").toString();
        response.sendRedirect(payInfo);

        return null;
    }
}
